package com.cb2.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <a href="https://leetcode.cn/problems/combination-sum-ii/">组合总和 II(Combination Sum II)</a>
 * <p>给定一个候选人编号的集合 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。</p>
 * <p>candidates 中的每个数字在每个组合中只能使用 一次 。</p>
 * <p>注意：解集不能包含重复的组合。 </p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1:
 *      输入: candidates = [10,1,2,7,6,1,5], target = 8,
 *      输出:
 *          [
 *          [1,1,6],
 *          [1,2,5],
 *          [1,7],
 *          [2,6]
 *          ]
 *
 * 示例 2:
 *      输入: candidates = [2,5,2,1,2], target = 5,
 *      输出:
 *          [
 *          [1,2,2],
 *          [5]
 *          ]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *  <ul>
 *      <li>1 <= candidates.length <= 100</li>
 *      <li>1 <= candidates[i] <= 50</li>
 *      <li>1 <= target <= 30</li>
 *  </ul>
 * </p>
 *
 * @author c2b
 * @see LC0039CombinationSum_M
 * @see LC0040CombinationSum_II_M
 * @see LC0216CombinationSum_III_M
 * @see LC0377CombinationSum_IV_M
 * @since 2025/2/12 13:29
 */
public class LC0040CombinationSum_II_M {
    static class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            List<List<Integer>> resList = new ArrayList<>();
            Arrays.sort(candidates);
            backtracking(candidates, target, 0, new ArrayList<>(), resList);
            return resList;
        }

        private void backtracking(int[] candidates, int target, int startIdx, List<Integer> path, List<List<Integer>> resList) {
            if (target == 0) {
                resList.add(new ArrayList<>(path));
                return;
            }
            for (int i = startIdx; i < candidates.length; i++) {
                // 数组是递增的，当前数 > target，后面的数也一定 > target。后面的计算无意义，直接跳出循环
                if (candidates[i] > target) {
                    break;
                }
                // 去重
                if (i > startIdx && candidates[i] == candidates[i - 1]) {
                    continue;
                }
                path.add(candidates[i]);
                // i +1 ，保证每个数字只使用一次
                backtracking(candidates, target - candidates[i], i + 1, path, resList);
                path.remove(path.size() - 1);   // 剪枝
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        Printer.printListListInteger(solution.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8));
        Printer.printListListInteger(solution.combinationSum2(new int[]{2, 5, 2, 1, 2}, 5));
    }
}
